class BlockingQueue<T> {
    private static instance: BlockingQueue<any> | null = null;
    private queue: T[] = [];
    private capacity: number;
    private waitingConsumers: (() => void)[] = [];
    private waitingProducers: (() => void)[] = [];

    // 私有构造函数，防止外部直接创建实例
    private constructor(capacity: number) {
        this.capacity = capacity;
    }

    // 获取单例实例
    public static getInstance<T>(capacity: number): BlockingQueue<T> {
        if (!BlockingQueue.instance) {
            BlockingQueue.instance = new BlockingQueue<T>(capacity);
        }
        return BlockingQueue.instance;
    }

    // 向队列添加元素
    async enqueue(item: T): Promise<void> {
        if (this.queue.length >= this.capacity) {
            // 队列已满，等待直到有空间
            await new Promise<void>((resolve) => this.waitingProducers.push(resolve));
        }
        this.queue.push(item);

        // 如果有消费者等待，唤醒一个消费者
        if (this.waitingConsumers.length > 0) {
            const consumer = this.waitingConsumers.shift();
            consumer?.();
        }
    }

    // 从队列中取出元素
    async dequeue(): Promise<T> {
        if (this.queue.length === 0) {
            // 队列为空，等待直到有元素
            await new Promise<void>((resolve) => this.waitingConsumers.push(resolve));
        }

        const item = this.queue.shift()!;

        // 如果有生产者等待，唤醒一个生产者
        if (this.waitingProducers.length > 0) {
            const producer = this.waitingProducers.shift();
            producer?.();
        }

        return item;
    }

    // 队列的当前大小
    size(): number {
        return this.queue.length;
    }

    // 队列是否已满
    isFull(): boolean {
        return this.queue.length >= this.capacity;
    }

    // 队列是否为空
    isEmpty(): boolean {
        return this.queue.length === 0;
    }
}